import Handler = Laya.Handler;

import WxSdk from "../sdk/WxSdk";
import Http from "./Http";
import CommonConfig from '../global/CommonConfig';

/**
 * Http请求后端接口封装
 */
export default class RequestServer {
    constructor() {

    }

    /**
     * 登录
     * @param onSuccess 成功回调，会把返回内容传入第一个参数
     * @param onFailed 失败回调
     */
    public static Login(onSuccess: Function, onFailed: Function = null): void {
        if (WxSdk.isInWxDev()) {
            WxSdk.wxLogin(Handler.create(null, (res) => {
                let token = res.code;
                let url = CommonConfig.serverHost + '/account/login';
                Http.Post(url, { game_id: CommonConfig.gameId, token: token }, onSuccess, onFailed);
            }), Handler.create(null, onFailed));
        } else {
            let url = CommonConfig.serverHost + '/devaccount/login';
            Http.Post(url, { game_id: CommonConfig.gameId, token: CommonConfig.devWxOpenId }, onSuccess, onFailed)
        }
    }


    /**
     * 获取数据
     * @param key 数据的key，多个用逗号隔开
     * @param onSuccess 成功回调
     * @param onFailed 失败回调
     */
    public static getData(key: string, onSuccess: Function, onFailed: Function = null): void {
        let url = `${CommonConfig.serverHost}/account/getdata?key=${key}`;
        Http.Get(url, null, onSuccess, onFailed);
    }

    /**
     * 保存数据
     * @param data 保存的数据，后台会分开key保存
     * @param onSuccess 成功回调
     * @param onFailed 失败回调
     */
    public static saveData(data: any, onSuccess: Function, onFailed: Function = null): void {
        let url = CommonConfig.serverHost + '/account/savedata';
        Http.Post(url, data, onSuccess, onFailed);
    }

    /**
     * 被邀请接口
     * @param fromOpenId 主动邀请的用户的openId
     * @param extraData 前端自定义数据
     * @param onSuccess 成功回调
     * @param onFailed 失败回调
     */
    public static invited(fromOpenId: string, extraData: any, onSuccess: Function, onFailed: Function = null): void {
        let url = CommonConfig.serverHost + '/account/invited';
        let postData = {
            from_open_id: fromOpenId,
            extra_data: extraData
        };
        Http.Post(url, postData, onSuccess, onFailed);
    }

    /**
     * 请求version接口，包含服务器地址，提审开关等信息
     * @param onSuccess 成功回调
     * @param onFailed 失败回调
     */
    public static version(onSuccess: Function, onFailed: Function) {
        let url = `${CommonConfig.serverHost}/version_info/game_id/${CommonConfig.gameId}/version/${CommonConfig.clientVersion}`;
        Http.Get(url, null, onSuccess, onFailed);
    }
}